from django.contrib import admin
from django_celery_beat.models import PeriodicTask
from django_celery_beat.admin import PeriodicTaskAdmin as OPeriodicTaskAdmin
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.conf.urls import url
import json


class PeriodicTaskAdmin(OPeriodicTaskAdmin):
    search_fields = ('name', 'task', 'args')
    list_display = ('get_name', 'task', 'rule', 'args', 'enabled', 'get_date_changed', 'single_column_action')

    def rule(self, obj):
        return obj.interval if obj.interval else  obj.crontab

    rule.short_description = "规则"

    def get_name(self, obj):
        return obj.name

    get_name.short_description = '标题'

    def get_date_changed(self, obj):
        return obj.date_changed

    get_date_changed.short_description = '修改日期'

    def single_column_action(self, obj):
        return '<a class="button disable trigger_task" href="{}">删除</a>|<a class="button" href="#">执行记录</a>'.format(
            reverse('admin:manual_trigger_task', args=[obj.pk]))

    single_column_action.short_description = '操作'
    single_column_action.allow_tags = True

    # add custom static resource
    class Media:
        js = ['/static/proj/js/django_celery_beat.js']

    # add custom admin url
    def get_urls(self):
        urls = super(PeriodicTaskAdmin, self).get_urls()
        my_urls = [
            # url(r'^my_view/$', self.manual_trigger_task_view),
            url(r'^admin/django_celery_beat/periodictask/(?P<id>\d+)/manual_trigger/$', self.manual_trigger_task_view,
                name='manual_trigger_task'),
        ]
        return my_urls + urls

    def manual_trigger_task_view(self, request, pk):
        """
        手工触发任务
        """
        # if not (request.user.is_authenticated() and request.user.has_perm('django_celery_beat.manual_trigger_task')):
        #     from django.contrib.auth import PermissionDenied
        #     raise PermissionDenied()
        p = get_object_or_404(PeriodicTask, pk=int(pk))
        import importlib
        module_name = importlib.import_module('proj.tasks')  # 动态加载模块
        func_name = p.task  # 模块中的函数名
        func_args = json.loads(p.args)  # 参数
        if hasattr(module_name, func_name):
            func = getattr(module_name, func_name)  # 获取函数指针
            func.delay(*func_args)  # 调用
        else:
            raise AttributeError()


admin.site.unregister(PeriodicTask)
admin.site.register(PeriodicTask, PeriodicTaskAdmin)
